<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="->">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesdialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="roleList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['bottom-border', i1 === 0 ? 'top-boder' : '', 'vcenter']"
              v-for="(item1, i1) in scope.row.children"
              v-bind:key="item1.id"
            >
              <el-col :span="5">
                <el-tag closable @close="closeRoles(scope.row, item1.id)">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="([i2 === 0 ? '' : 'top-boder'], 'vcenter')"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="closeRoles(scope.row, item2.id)"
                    >
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="danger"
                      closable
                      @close="closeRoles(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="editRole(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              circle
              @click="delRole(scope.row.id)"
            ></el-button>
            <el-tooltip
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                circle
                @click="setRightsDiagle(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限弹出框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightsdialogVisible"
      width="50%"
      @close="colseSetRights"
    >
      <el-tree
        :data="rightsList"
        :props="defaultProps"
        default-expand-all
        node-key="id"
        show-checkbox
        :default-checked-keys="defKey"
        ref="treeRef"
      ></el-tree>
      <span slot="footer">
        <el-button @click="setRightsdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRights">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加角色 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesdialogVisible"
      width="50%"
    >
      <el-form
        :model="addRolesForm"
        :rules="addRolesrules"
        ref="addRolesRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="addRolesdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleBtn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRolesdialogVisible"
      width="50%"
    >
      <el-form
        :model="editRolesForm"
        :rules="editRolesrules"
        ref="editRolesRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="editRolesdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleList: [],
      // 分配权限弹出框子弹
      setRightsdialogVisible: false,
      // 权限列表
      rightsList: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的
      defKey: [],
      // 获取角色id
      roleID: '',
      // 添加角色弹出框
      addRolesdialogVisible: false,
      // 添加角色对象
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色校验规则
      addRolesrules: {
        roleName: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ],
        roleDesc: [
          { required: false, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      // 编辑角色弹框
      editRolesdialogVisible: false,
      editRolesForm: {},
      editRolesrules: {
        roleName: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ],
        roleDesc: [
          { required: false, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      this.roleList = res.data
      // console.log(res)
    },
    async closeRoles(role, rightid) {
      const confireRes = await this.$confirm(
        '此操作将永久删除, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      if (confireRes !== 'confirm') return this.$message.info('已取消')
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightid}`
      )
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      role.children = res.data
    },
    // 分配权限弹框
    async setRightsDiagle(roles) {
      this.roleID = roles.id
      const { data: res } = await this.$http.get('rights/tree')
      console.log(res)
      this.rightsList = res.data
      this.defSelectKeys(roles, this.defKey)
      this.setRightsdialogVisible = true
    },
    // 获取默认选中的
    defSelectKeys(role, arr) {
      if (!role.children) {
        return arr.push(role.id)
      }
      role.children.forEach((element) => {
        this.defSelectKeys(element, arr)
      })
    },
    colseSetRights() {
      this.defKey = []
    },
    // 分配权限id
    async setRights() {
      const keyArr = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const keysStr = keyArr.join(',')
      // console.log(keysStr)
      const { data: res } = await this.$http.post(
        `roles/${this.roleID}/rights`,
        { rids: keysStr }
      )
      // console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getRoleList()
      this.setRightsdialogVisible = false
    },
    // 添加角色
    addRoleBtn() {
      this.$refs.addRolesRef.validate(async (valid) => {
        if (!valid) return false
        const { data: res } = await this.$http.post('roles', this.addRolesForm)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getRoleList()
      })
      this.addRolesdialogVisible = false
    },
    // 编辑角色
    async editRole(id) {
      const { data: res } = await this.$http.get('roles/' + id.id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.editRolesForm = res.data
      this.editRolesdialogVisible = true
    },
    editRoleBtn() {
      this.$refs.editRolesRef.validate(async (valid) => {
        if (!valid) {
          return false
        }
        const { data: res } = await this.$http.put(
          `roles/${this.editRolesForm.roleId}`,
          {
            roleName: this.editRolesForm.roleName,
            roleDesc: this.editRolesForm.roleDesc
          }
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.getRoleList()
      })
      this.editRolesdialogVisible = false
    },
    // 删除角色
    async delRole(id) {
      const confirmRes = await this.$confirm(
        '此操作将永久删除该条数据, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)
      console.log(confirmRes)
      if (confirmRes !== 'confirm') {
        return this.$message.error('已取消')
      }
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
      this.getRoleList()
    }
  }
}
</script>
<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.top-boder {
  border-top: 1px solid #ddd;
}
.bottom-border {
  border-bottom: 1px solid #ddd;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
